<?php

final class App{

    public static function run(){
        self::_int();
        self::_set_url();
        spl_autoload_register([__CLASS__,"_autoload"]);
        self::_create_demo();
        self::_run();
    }

    /**
     * 设置外部url
     */
    private static function _set_url(){
        define("PUBLIC",ROOT_PATH . "/Public");
        define("UPLOADS",ROOT_PATH . "/Uploads");
    }

    private static function _run(){
        $c= trim(ucfirst($_GET['c'] ?? "Index"));
        $a= trim($_GET['a'] ?? "index");
        define("CONTROLLER_NAME",$c);
        define("ACTION_NAME",$a);

        $c.="Controller";
        $class=new $c();
        if(method_exists($class,$a)){
            $class->$a();
        }else{
            die( $a . "方法不存在 (: !");
        }
    }

    /**自动载入功能
     * @param $classname
     */
    private static function _autoload($classname){
        switch (true){
            case substr($classname,-10)=="Controller":
                $path=APP_CONTROLLER_PATH . "/" . $classname . ".class.php";
                if(!is_file($path)){
                    die( $classname . "类不存在！请先创建类文件 (: !");
                }
                include APP_CONTROLLER_PATH . "/" . $classname . ".class.php";
                break;
            default :
                include ORG_PATH . "/" . $classname . ".class.php";
        }

    }

    /**
     * 创建demo文件
     */
    private static function _create_demo(){
        $path = APP_CONTROLLER_PATH . "/IndexController.class.php";
        $str = <<<EOF
<?PHP
 
class IndexController extends Controller{


    public function index(){
        echo "<h1 style=\"margin:auto;line-height:300px;text-align: center\">欢迎使用 HAPPY 框架 (: !</h1>";
    }
 }
 
 ?>
EOF;
        is_file($path)  or file_put_contents($path , $str);

    }
    /**
     * 初始化框架
     */
    private static function _int(){
        //加载框架配置文件
        C(include CONFIG_PATH . "/config.php");
        //加载用户配置文件
        $user_config  =  APP_CONFIG_PATH . "/config.php";
        $str = <<<EOF
<?php

//配置项 => 配置值
return [
    
];
EOF;
        is_file($user_config)  or file_put_contents($user_config , $str);
        C(include $user_config);
    }
}